package com.tz.system.user.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tz.platform.common.CacheConstans;
import com.tz.platform.common.Constants;
import com.tz.platform.page.PageCondition;
import com.tz.platform.utils.MD5Util;
import com.tz.platform.utils.PasswordManage;
import com.tz.platform.utils.ReturnUtil;
import com.tz.system.cache.service.ParameterCache;
import com.tz.system.user.dao.TMgtUserDao;
import com.tz.system.user.model.TMgtUser;
import com.tz.system.user.service.TMgtUserService;
import com.tz.system.user.service.UserRoleService;

@Service("tMgtUserServiceImpl")
@Transactional
public class TMgtUserServiceImpl implements TMgtUserService {
	
	@Autowired
	private ParameterCache parameterCache;   //加载缓存
	
	@Autowired
	private TMgtUserDao tMgtUserDao;

	@Autowired
	private UserRoleService userRoleService;

	// 查询分页
	private static String queryPageTMgtUserHql = " from TMgtUser ";

	// 根据用户ID获取用户信息
	private static String queryByUserId = queryPageTMgtUserHql + "where userId=? ";

	//根据用户id和密码查询有效的用户信息
	private static String checkUserHql = " from TMgtUser where userId=? and userPassword=? and userStatus=?";

	private static String queryAllValidUserHql = queryPageTMgtUserHql + " where userStatus=?";

	@Override
	@Transactional
	public Map<String,Object> removeById(Integer id) {
		try {
			TMgtUser entity = this.queryById(id);
			tMgtUserDao.removeById(id);
			// 删除用户对应的角色信息
			userRoleService.removeUserRoleByUserId(entity.getUserId());
			//重新加载缓存
			parameterCache.deleteRedis(CacheConstans.USERS, entity.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnUtil.returnMessage("fail", "删除失败！");
		}
		return ReturnUtil.returnMessage("success", "删除成功！");
	}

	@Override
	@Transactional
	public Map<String,Object> addSave(TMgtUser entity) {
		//1、查询用户id是否存在
		TMgtUser tUser = this.queryByUserId(entity.getUserId());
		if(tUser!=null){
			return ReturnUtil.returnMessage("fail", "该用户名已存在！");
		}
		try {
			entity.setUserPassword(MD5Util.EncodeString(Constants.DEFAULT_PASSWORD));
			tMgtUserDao.save(entity);
			// 重置用户缓存
			parameterCache.loadRedis(CacheConstans.USERS, entity.getUserId(), entity);
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnUtil.returnMessage("fail", "添加失败！");
		}
		return ReturnUtil.returnMessage("success", "添加成功！");
	}

	@Override
	@Transactional
	public Map<String,Object> updateSave(TMgtUser entity) {
		try {
			tMgtUserDao.saveOrUpdate(entity);
			// 重置用户缓存
			parameterCache.loadRedis(CacheConstans.USERS, entity.getUserId(), entity);
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnUtil.returnMessage("fail", "更新失败！");
		}
		return ReturnUtil.returnMessage("success", "更新成功！");
	}

	@Override
	@Transactional
	public void updateSaveRole(TMgtUser entity, String roleCode) {
		// 保存用户角色信息
		userRoleService.setUserRole(entity.getUserId(), roleCode);
		//重置用户缓存
		parameterCache.loadUserRoles(entity.getUserId());
		
	}

	@Override
	@Transactional
	public TMgtUser queryById(Integer id) {
		return tMgtUserDao.get(id);
	}

	@Override
	@Transactional
	public TMgtUser queryByUserId(String userId) {
		TMgtUser user = tMgtUserDao.findUnique(queryByUserId, userId);
		if (user == null) {
			return null;
		}
		return user;
	}

	@Override
	@Transactional
	public TMgtUser queryValidUserByUserId(String userId) {
		List<TMgtUser> users = tMgtUserDao.find(queryAllValidUserHql + " and userId=?", "B3001", userId);
		if (users == null || users.size() == 0) {
			return null;
		}
		return users.get(0);
	}

	@Override
	@Transactional
	public List<TMgtUser> queryAll() {
		List<TMgtUser> userList = tMgtUserDao.find(queryPageTMgtUserHql);
		return userList;
	}

	@Override
	@Transactional
	public List<TMgtUser> queryAllValidUser() {
		List<TMgtUser> userList = tMgtUserDao.find(queryAllValidUserHql, "B3001");
		return userList;
	}


	@Override
	@Transactional
	public Map<String, Object> updatePasswd(String userId, String oldPasswd, String newPasswd) {
		
		TMgtUser user = new TMgtUser();
		try {
			user = tMgtUserDao.findUnique(checkUserHql, userId, MD5Util.EncodeString(oldPasswd));
			if (user == null) {
				return ReturnUtil.returnMessage("failed", Constants.PASSWORD_MESSAGE_ERROR);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		PasswordManage pwdManage = new PasswordManage();
		if (pwdManage.getPwdSecurityLevel().equals("hight")) {
			if (!newPasswd.matches(pwdManage.getPwdSecurityHigh())) {
				return ReturnUtil.returnMessage("failed", Constants.PASSWORD_MESSAGE_HIGHT);
			}
		} else if (pwdManage.getPwdSecurityLevel().equals("mid")) {
			if (!newPasswd.matches(pwdManage.getPwdSecurityMid())) {
				return ReturnUtil.returnMessage("failed", Constants.PASSWORD_MESSAGE_MID);
			}
		} else {
			if (!newPasswd.matches(pwdManage.getPwdSecurityLow())) {
				return ReturnUtil.returnMessage("failed", Constants.PASSWORD_MESSAGE_LOW);
			}
		}

		try {
			user.setOldUserPassword(MD5Util.EncodeString(oldPasswd));
			user.setUserPassword(MD5Util.EncodeString(newPasswd));
			tMgtUserDao.saveOrUpdate(user);
			parameterCache.loadRedis(CacheConstans.USERS, userId, user);
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnUtil.returnMessage("fail", "重置密码失败！");
		}
		return ReturnUtil.returnMessage("success", "重置密码成功！");
	}
	
	@Override
	public String toResetPassWord(){
		String message = "";
		PasswordManage pwdManage = new PasswordManage();
		if (pwdManage.getPwdSecurityLevel().equals("hight")) {
			message = Constants.PASSWORD_MESSAGE_HIGHT;
		} else if (pwdManage.getPwdSecurityLevel().equals("mid")) {
			message = Constants.PASSWORD_MESSAGE_MID;
		} else {
			message = Constants.PASSWORD_MESSAGE_LOW;
		}
		return message;
	}

	@Override
	public Map<String, Object> resetPasswordById(Integer id) {
		String plainPass = Constants.DEFAULT_PASSWORD;
		try {
			TMgtUser user = this.queryById(id);
			if(user!=null){
				String encodeString = MD5Util.EncodeString(plainPass);
				String hql = "update TMgtUser set userPassword=? where id=?";
				tMgtUserDao.executeByHql(hql, encodeString, id);
				//重置用户缓存
				parameterCache.loadRedis(CacheConstans.USERS, user.getUserId(), user);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnUtil.returnMessage("fail", "重置密码失败！");
		}
		return ReturnUtil.returnMessage("success", "重置密码成功，新密码：【"+Constants.DEFAULT_PASSWORD+"】");
	}

	@Override
	@Transactional
	public boolean isUserIdSafe(TMgtUser user) {
		// 判断用户ID是否存在SQL注入
		String strHackerCode = "'<:>:;:(:):%:&:--";
		String strHackerArray[] = strHackerCode.split(":");
		for (int i = 0; i < strHackerArray.length; i++) {
			if (user.getUserId().indexOf(strHackerArray[i]) != -1) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 产生8位随机数（包含字母，数字）
	 * @return
	 */
	public String getRandomNums(){
		String result = "";
		String s = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		Random r = new Random();
		for (int i =0; i < 8; i++ ){
			 int n = r.nextInt(62);
			 result += s.substring(n, n+1);
		}
		return result;
	}

	@Override
	public List<TMgtUser> queryUserByInstCodeAndRoleCode(String instCode, String roleCode) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PageCondition findByPage(PageCondition condition) {
		return tMgtUserDao.findByPage(queryPageTMgtUserHql , condition);
	}
	
	
	
}
